import {
  type Ref,
  ref,
  reactive,
  toRaw,
  onMounted,
  h,
  watch,
  computed
} from "vue";
import { useRoute } from "vue-router";
import viewForm from "../viewForm.vue";
import editForm from "../form.vue";
import { usePublicHooks } from "@/views/hooks";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import userAvatar from "@/assets/normal-img.png";
import { getFullUrl } from "@/utils/auth";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {
  getPoiPage,
  createPoi,
  updatePoi,
  deletePoi,
  type PoiDTO
} from "@/api/poi";
const { peripheryTypeStyle } = usePublicHooks();
import dayjs from "dayjs";
export function usePeriphery(tableRef: Ref) {
  const route = useRoute();
  const form = reactive({
    queryStartTime: "",
    queryEndTime: dayjs().format("YYYY-MM-DD 23:59:59"),
    pageNum: 1,
    pageSize: 10,
    orderByColumn: "",
    isAsc: "asc",
    name: "",
    poiType: "",
    recommendationScore: NaN
  });
  const formRef = ref();
  const pageTitle = computed(() => {
    return `周边${peripheryTypeStyle.value(form.poiType)?.text || ""}信息管理`;
  });
  const dataList = ref([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  // 分页配置
  const pagination = reactive({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  // 表格列配置
  const columns: TableColumnList = [
    {
      label: "周边信息",
      prop: "name",
      headerAlign: "left",
      align: "left",
      cellRenderer: ({ row }) => (
        <div class="cursor-pointer">
          <el-image
            fit="cover"
            preview-teleported={true}
            src={row.coverImageUrl ? getFullUrl(row.coverImageUrl) : userAvatar}
            preview-src-list={Array.of(
              row.coverImageUrl ? getFullUrl(row.coverImageUrl) : userAvatar
            )}
            class="w-[24px] h-[24px] rounded-[5px] align-middle mr-2"
          />
          <span>{row.name}</span>
        </div>
      ),
      minWidth: 180
    },
    {
      label: "类型",
      prop: "poiType",
      minWidth: 100,
      hide: true,
      width: "100px",
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={peripheryTypeStyle.value(row.poiType).style}
        >
          {peripheryTypeStyle.value(row.poiType).text}
        </el-tag>
      )
    },
    // {
    //   label: "是否推荐",
    //   cellRenderer: scope => (
    //     <el-switch
    //       size={scope.props.size === "small" ? "small" : "default"}
    //       v-model={scope.row.recommend}
    //       active-text="推荐"
    //       inactive-text="不推荐"
    //       inline-prompt
    //       style={switchStyle.value}
    //     />
    //   )
    // },
    { label: "地址", prop: "address", align: "left" },
    {
      label: "简介",
      prop: "introduction",
      align: "left",
      minWidth: 320,
      cellRenderer: scope => (
        <div
          class="overflow-hidden whitespace-nowrap w-[320px] cursor-pointer text-ellipsis"
          onClick={() => onViewDetail(scope.row as any)}
        >
          {scope.row.introduction}
        </div>
      )
    },
    {
      label: "经纬度",
      prop: "longitude",
      minWidth: 180,
      width: 180,
      cellRenderer: ({ row }) => (
        <span>{(row.longitude || "") + "-" + (row.latitude || "")}</span>
      )
    },
    { label: "排序", prop: "recommendationScore" },
    // { label: "创建时间", prop: "CreateDate" },
    // { label: "创建人", prop: "CreateUserName" },
    // {
    //   label: "有效",
    //   cellRenderer: scope => (
    //     <el-switch
    //       size={scope.props.size === "small" ? "small" : "default"}
    //       v-model={scope.row.EnabledMark}
    //       active-value={1}
    //       inactive-value={0}
    //       active-text="禁止"
    //       inactive-text="允许"
    //       inline-prompt
    //       style={switchStyle.value}
    //     />
    //   )
    // },
    // { label: "备注", prop: "Description" },
    {
      label: "操作",
      fixed: "right",
      width: "240px",
      slot: "operation" // 包含编辑、删除等操作
    }
  ];
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagination.pageSize = val;
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    form.pageNum = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    console.log(`handleSelectionChange: ${val}`);
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空周边信息的选择
    tableRef.value.getTableRef().clearSelection();
  }
  function onViewDetail(row) {
    addDialog({
      title: row.name,
      props: {
        formInline: {
          ...row
        }
      },
      width: "720px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: false,
      hideFooter: true,
      closeOnClickModal: false,
      contentRenderer: () => h(viewForm, { ref: formRef, formInline: null })
    });
  }

  /** 批量删除 */
  function onBatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    if (!curSelected.length) {
      message("请选择要删除的记录", { type: "warning" });
      return;
    }
    const Ids = curSelected.map(item => item.id);
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    deletePoi(Ids).then(() => {
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    });
    message(`已删除周边信息编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
  }
  // 获取周边信息列表
  async function onSearch() {
    loading.value = true;
    const { data } = await getPoiPage(toRaw(form));
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.size;
    pagination.currentPage = data.current;
    setTimeout(() => (loading.value = false), 500);
  }
  // 新增/编辑周边信息
  function openDialog(type: string, row?: PoiDTO) {
    const title = type === "add" ? "新增" : "编辑";
    addDialog({
      title: `${title}周边信息`,
      props: {
        formInline: {
          id: row?.id || "",
          name: row?.name || "",
          poiType: row?.poiType || form.poiType,
          longitude: row?.longitude || "",
          latitude: row?.latitude || "",
          address: row?.address || "",
          introduction: row?.introduction || "",
          coverImageUrl: row?.coverImageUrl || null,
          recommendationScore: row?.recommendationScore || 1
          // DeleteMark: row?.DeleteMark || 1,
          // EnabledMark: row?.EnabledMark || 0,
          // Description: row?.Description || "",
          // CreateUserName: row?.CreateUserName || ""
        }
      },
      width: "720px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as PoiDTO;
        async function chores() {
          message(`您${title}了周边信息名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          await onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (type === "add") {
              delete curData.id;
              await createPoi(curData);
              await chores();
            } else {
              // 编辑周边信息
              curData.id = row.id;
              await updatePoi(curData);
              await chores();
            }
          }
        });
      }
    });
  }
  // 删除周边信息
  function handleDelete(row) {
    // ElMessageBox.confirm(`确认删除周边信息【${row.name}】?`, "删除确认", {
    //   type: "warning"
    // }).then(() => {
    deletePoi(row.id).then(() => {
      message(`删除周边信息 ${row.name} 成功`, { type: "success" });
      // 重置分页到第一页
      pagination.currentPage = 1;
      onSearch();
    });
    // });
  }
  onMounted(async () => {
    // 初始化时设置类型参数
    form.poiType = (route.meta.poiType as string) || "";
    onSearch();
  });
  // 监听路由变化，更新类型参数
  watch(
    () => route.meta.poiType,
    newType => {
      form.poiType = (newType as string) || "";
      // 重置页码并重新搜索
      pagination.currentPage = 1;
      form.pageNum = 1;
      onSearch();
    }
  );
  return {
    form,
    pageTitle,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onBatchDel,
    onSearch,
    onViewDetail,
    resetForm,
    openDialog,
    handleDelete,
    onSelectionCancel,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
